<template>
  <el-card style="height: 710px; width: 100%;">
    <div class="tou">
      <!-- 条件查询 -->

      <el-form>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据编号：" style="margin-bottom: 0;">
              <el-input v-model="retail.number" placeholder="请输入单据编号" style="width: 280px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品信息：" style="margin-bottom: 0;">
              <el-input v-model="retail.commodities" placeholder="请输入条码、名称、规格、型号、颜色、扩展信息"
                style="width: 280px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据日期：" style="margin-bottom: 0;">
              <div class="demo-date-picker">
                <div class="block">
                  <el-date-picker v-model="billDate" style="width: 280px;" format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange" range-separator="~" value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始时间"
                    end-placeholder="结束时间" prefix-icon="display" />
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">

            <el-form-item>
              <el-button type="primary" @click="init">查询</el-button>
              <el-button @click="cz">重置</el-button>
              <a style="margin-left: 8px;" @click="ss">
                {{ linkText }}
                <i class="anticon " v-show="!isDivVisible">
                  <svg viewBox="64 64 896 896" data-icon="down" width="1em" height="1em" fill="currentColor"
                    aria-hidden="true" focusable="false" class="">
                    <path
                      d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z">
                    </path>
                  </svg>
                </i>
                <i class="anticon" v-show="isDivVisible">
                  <svg viewBox="64 64 896 896" data-icon="up" width="1em" height="1em" fill="currentColor"
                    aria-hidden="true" focusable="false" class="">
                    <path
                      d="M890.5 755.3L537.9 269.2c-12.8-17.6-39-17.6-51.7 0L133.5 755.3A8 8 0 0 0 140 768h75c5.1 0 9.9-2.5 12.9-6.6L512 369.8l284.1 391.6c3 4.1 7.8 6.6 12.9 6.6h75c6.5 0 10.3-7.4 6.5-12.7z">
                    </path>
                  </svg>
                </i>
              </a>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-show="isDivVisible">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="会员卡号：">
                <el-select v-model="retail.supId" placeholder="请选择供应商" style="width: 280px;">
                  <el-option v-for="item in suppliers" :key="item.supId" :label="item.supName" :value="item.supId" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="仓库名称：">
                <el-select v-model="retail.depId" clearable style="width: 280px; ">
                  <el-option v-for="item in depots" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="操作员：">
                <el-select v-model="retail.userId" placeholder="请选择操作员" style="width: 280px;">
                  <el-option v-for="item in users" :key="item.value" :label="item.username" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="结算账户：">
                <el-select v-model="retail.accId" clearable style="width: 280px; margin-left: 10px;">
                  <el-option v-for="account in accounts" :key="account.id" :label="account.name"
                    :value="account.accId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单据状态：">
                <el-select v-model="retail.status" placeholder="请选择单据状态" style="width: 280px;">
                  <el-option v-for="item in docStatus" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单据备注：">
                <el-input v-model="retail.remark" placeholder="请输入单据备注" style="width: 280px;"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!-- 新增和批量操作 -->
      <el-button class="ant-btn ant-btn-primary" v-perm:retail:retail_back:insert="insert">
        <i class="anticon">
          <svg viewBox="64 64 896 896" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true"
            focusable="false" class="">
            <path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path>
            <path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path>
          </svg>
        </i>
        <span style="margin-left: 8px;">
          新增
        </span>
      </el-button>
      <el-dropdown>
        <el-button class="ant-btn" style="margin-left: 8px;">
          批量操作<el-icon>
            <ArrowDown />
          </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <template v-for="item in strBtn">
              <template v-if="item === '编辑'">
                <el-dropdown-item @click="removes">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  <span>删除</span>
                </el-dropdown-item>
              </template>
              <template v-else-if="item === '审核'">
                <el-dropdown-item @click="modifyTheState(1)">
                  <el-icon>
                    <Select />
                  </el-icon>
                  <span>{{ item }}</span>
                </el-dropdown-item>
              </template>
              <template v-else>
                <el-dropdown-item @click="modifyTheState(0)">
                  <el-icon>
                    <CircleClose />
                  </el-icon>
                  <span>{{ item }}</span>
                </el-dropdown-item>
              </template>

            </template>
            <!-- <el-dropdown-item @click="modifyTheState(1)">
              <el-icon>
                <Select />
              </el-icon>
              <span>审核</span>
            </el-dropdown-item>
            <el-dropdown-item @click="modifyTheState(0)">
              <el-icon>
                <CircleClose />
              </el-icon>
              <span>反审核</span>
            </el-dropdown-item> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 分页内容显示 -->
      <div style="margin-top: 6px;">
        <el-table :data="page.records" border stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="操作" min-width="120" align="center" width="220">
            <template #default="scope">
              <el-button link type="primary" :row="scope.row" v-perm:retail:retail_back:check="checkRetail">
                查看
              </el-button>
              <el-button link type="primary" :row="scope.row" v-perm:retail:retail_back:update="update">
                编辑
              </el-button>
              <el-button link type="primary" :row="scope.row" v-perm:retail:retail_back:copy="toCopy">
                复制
              </el-button>
              <el-button link type="primary" :row="scope.row" v-perm:retail:retail_back:delete="remove">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="showIdColumn" prop="id" label="id" width="170" />
          <el-table-column prop="supName" width="200" label="会员"></el-table-column>
          <el-table-column prop="number" width="150" label="单据编号"></el-table-column>
          <el-table-column prop="materialName" width="200" label="商品信息">
          </el-table-column>
          <el-table-column prop="operTime" width="200" label="单据日期"></el-table-column>
          <el-table-column prop="username" width="150" label="操作员"></el-table-column>
          <el-table-column prop="totalQuantity" width="150" label="数量"></el-table-column>
          <el-table-column prop="totalPrice" width="150" label="金额合计"></el-table-column>
          <el-table-column prop="changeAmount" width="150" label="收款金额"></el-table-column>
          <el-table-column prop="backAmount" width="150" label="找零"></el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status == 0" type="danger" effect="light">
                未审核
              </el-tag>
              <el-tag v-else type="success" effect="light">
                已审核
              </el-tag>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <el-pagination v-model:page-size="page.size" v-model:current-Page="page.current" @current-change="init"
        @size-change="init" :page-sizes="[5, 10, 15]" layout="total, prev, pager, next, sizes, jumper"
        :total="page.total" style="float: right;margin-top: 10px;">
      </el-pagination>
      <!-- 弹框 -->
      <el-dialog :title="title" v-model="visible" width="80%" top="20vh" :destroy-on-close="true">
        <router-view :data="data" @close="close"></router-view>
      </el-dialog>
    </div>
  </el-card>
</template>

<script setup>
import { ref, defineProps } from 'vue';
import router from '@/router';
import request from '@/api/request'
import { ElMessage } from 'element-plus';

const props = defineProps(['strBtn'])
let page = ref([])
let visible = ref(false)
let title = ref("")
let data = ref({})
let linkText = ref('展开')
let isDivVisible = ref(false)
//时间
let billDate = ref([])

//供应商
let suppliers = ref([])
//操作员
let users = ref([])
//单据状态
let docStatus = [
  {
    value: 0,
    label: '未审核',
  },
  {
    value: 1,
    label: '已审核',
  },
  {
    value: 2,
    label: '已审核',
  }
]

let retail = ref({})
//初始化
let init = () => {
  console.log("结算" + retail.value.accId)
  console.log("仓库" + retail.value.depId)
  console.log("供应商" + retail.value.supId)
  if (billDate.value) {
    retail.value.startTime = billDate.value[0];
    retail.value.endTime = billDate.value[1];
  }
  retail.value.current = page.value.current;
  retail.value.size = page.value.size;
  request({
    url: '/retail/select2',
    method: "post",
    data: retail.value
  }).then(res => {
    page.value = res.data
  })
}
init();

//重置
let cz = () => {
  retail.value = ({})
  billDate.value = ([])
  init();
}

//查询供应商
let findsuppliers = () => {
  request({
    url: '/basic/vendor/findSupplier3',
    method: 'get'
  }).then(resp => {
    suppliers.value = resp.data
  })
}
findsuppliers();

// 仓库查询
const depots = ref([]);
const loadDepot = () => {
  request({
    url: '/depot/list',
    method: 'get'
  }).then(res => {
    depots.value = res.data; // 更新仓库数据
  }).catch(err => {
    console.error(err);
  });
};
loadDepot();

const accounts = ref([]); // 存储结算账户数据
const loadAccounts = () => {
  request({
    url: '/basic/account/list',
    method: 'get'
  }).then(res => {
    console.log(res);
    accounts.value = res.data; // 更新结算账户数据
  }).catch(err => {
    console.error(err);
  });
};
loadAccounts();

//查询操作员
let findusers = () => {
  request({
    url: '/user/user',
    method: 'get'
  }).then(resp => {
    users.value = resp.data
  })
}
findusers();

let ss = () => {
  isDivVisible.value = !isDivVisible.value;
  linkText.value = isDivVisible.value ? '收起' : '展开'
}

//跳转新增页面
let insert = (menu) => {
  title.value = "新增";
  visible.value = true;
  router.push(menu.path);
};

//跳转查看页面
let checkRetail = (menu, row) => {
  title.value = '零售退货入库-详情';
  visible.value = true;
  data.value = row;
  router.push(menu.path);
}

// 跳转复制新增页面
const toCopy = (p, row) => {
  title.value = '复制新增';
  visible.value = true;

  // 深拷贝原有行数据
  data.value = JSON.parse(JSON.stringify(row)); // 确保深拷贝
  data.value.number = ''; // 清空单据编号，以避免重复
  router.push(p.path);
};
//跳转修改页面
let update = (menu, row) => {
  title.value = '编辑';
  visible.value = true;
  data.value = row;
  router.push(menu.path);
}


//多选值
let multipleSelection = ref([])
let ids = ref([]);

//获取多选的值转入multipleSelection中
let handleSelectionChange = (val) => {
  multipleSelection.value = val;
  ids.value = val.map(item => item.id);
}
//批量删除
let removes = () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请先选择至少一项记录');
    return;
  }

  let allApproved = true; // 假设所有选中的项都是未审核的
  multipleSelection.value.forEach(item => {
    if (item.status != 0) {
      console.log(item.status);
      ElMessage.warning('抱歉，只有未审核的单据才能删除！');
      allApproved = false; // 发现有已审核的项，设置标志为false
    }
  });

  if (allApproved) {
    request.delete("/sale/delete", {
      data: ids.value
    }).then(resp => {
      ElMessage.success(resp.data);
      init();
    }).catch(error => {
      ElMessage.error('删除失败，请重试！');
      console.error(error);
    });
  }
};

//审核
let modifyTheState = (num) => {
  console.log('天', num)
  if (ids.value.length === 0) {
    ElMessage.warning('请先选择至少一项记录');
    return;
  }

  let allApproved = true;
  if (num == 1) {
    multipleSelection.value.forEach(item => {
      if (item.status != 0) {
        ElMessage.warning('抱歉，只有未审核的单据才能审核！');
        allApproved = false;
        return;
      }
    });
  } else {
    multipleSelection.value.forEach(item => {
      if (item.status != 1) {
        ElMessage.warning('抱歉，只有已审核的单据才能反审核！');
        allApproved = false;
        return;
      }
    });
  }

  if (allApproved) {
    request.put("/purchase/order/modifyTheState", {
      ids: ids.value,
      status: num
    }).then(resp => {
      ElMessage.success(resp.data);
      init();
    }).catch(error => {
      ElMessage.error('操作失败，请重试！');
      console.error(error);
    });
  }
}


//删除
let remove = (menu, row) => {
  console.log(row.status)
  if (row.status != 0) {
    ElMessage.warning('抱歉，只有未审核的单据才能删除！');
    return;
  }
  request.delete("/retail/remove/" + row.id)
    .then(resp => {
      ElMessage.success(resp.data);
      init();
    });
};

let close = () => {
  init();
  visible.value = false;
}
</script>

<style scoped>
.tou {
  float: left;
  position: relative;
  width: 100%;
}

.el-form-item {
  margin-right: 12px;
  vertical-align: middle;
}

a:active,
a:hover {
  text-decoration: none;
  outline: 0;
}

a:hover {
  color: #40a9ff;
}

a {
  color: #1890ff;
  text-decoration: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  transition: color .3s;
  -webkit-text-decoration-skip: objects;
}

.anticon {
  display: inline-block;
  color: inherit;
  font-style: normal;
  line-height: 0;
  text-align: center;
  text-transform: none;
  vertical-align: -.125em;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.anticon svg {
  display: inline-block;
}

.ant-btn {
  line-height: 1.499;
  position: relative;
  display: inline-block;
  font-weight: 400;
  white-space: nowrap;
  text-align: center;
  background-image: none;
  border: 1px solid transparent;
  box-shadow: 0 2px 0 rgba(0, 0, 0, .015);
  cursor: pointer;
  transition: all .3s cubic-bezier(.645, .045, .355, 1);
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  height: 32px;
  padding: 0 15px;
  font-size: 14px;
  border-radius: 4px;
  color: rgba(0, 0, 0, .65);
  background-color: #fff;
  border-color: #d9d9d9;
}

.ant-btn:hover {
  color: #40a9ff;
  background-color: #fff;
  border-color: #40a9ff;
}

.ant-btn-primary {
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
  text-shadow: 0 -1px 0 rgba(0, 0, 0, .12);
  box-shadow: 0 2px 0 rgba(0, 0, 0, .045);
}

.ant-btn-primary:focus,
.ant-btn-primary:hover {
  color: #fff;
  background-color: #40a9ff;
  border-color: #40a9ff;
}
</style>
